<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="heritageName">
        <el-input
          v-model="queryParams.heritageName"
          placeholder="请输入非遗名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="编号" prop="heritageCode">
        <el-input
          v-model="queryParams.heritageCode"
          placeholder="请输入非遗编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类别" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择类别" clearable>
          <el-option
            v-for="item in categoryOptions"
            :key="item.categoryId"
            :label="item.categoryName"
            :value="item.categoryId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="级别" prop="level">
        <el-select v-model="queryParams.level" placeholder="请选择级别" clearable>
          <el-option
            v-for="dict in ichLevel?.value?.ich_level || []"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="地区" prop="area">
        <el-input
          v-model="queryParams.area"
          placeholder="请输入所属地区"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['ich:heritage:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ich:heritage:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ich:heritage:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['ich:heritage:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="heritageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="非遗ID" align="center" prop="heritageId" />
      <el-table-column label="非遗名称" align="center" prop="heritageName" :show-overflow-tooltip="true"/>
      <el-table-column label="非遗编号" align="center" prop="heritageCode" />
      <el-table-column label="类别" align="center" prop="category.categoryName" />
      <el-table-column label="级别" align="center" prop="level">
        <template #default="scope">
          <dict-tag :options="ichLevel?.value?.ich_level || []" :value="scope.row.level"/>
        </template>
      </el-table-column>
      <el-table-column label="所属地区" align="center" prop="area" />
      <el-table-column label="多媒体资料" align="center">
        <template #default="scope">
          <el-space>
            <el-popover
              v-if="scope.row.images && scope.row.images.length"
              placement="top"
              trigger="hover"
              width="300"
            >
              <template #reference>
                <el-button type="primary" link>
                  图片({{ scope.row.images.length }})
                </el-button>
              </template>
              <el-image-viewer
                v-if="showImageViewer"
                :url-list="scope.row.images"
                @close="showImageViewer = false"
              />
              <el-scrollbar height="300px">
                <el-image
                  v-for="(url, index) in scope.row.images"
                  :key="index"
                  :src="baseURL + '/' + url"
                  :preview-src-list="scope.row.images.map(url => baseURL + '/' + url)"
                  :initial-index="index"
                  fit="cover"
                  class="preview-image"
                  @click="showImageViewer = true"
                />
              </el-scrollbar>
            </el-popover>
            <el-popover
              v-if="scope.row.videos && scope.row.videos.length"
              placement="top"
              trigger="hover"
              width="300"
            >
              <template #reference>
                <el-button type="success" link>
                  视频({{ scope.row.videos.length }})
                </el-button>
              </template>
              <el-scrollbar height="300px">
                <div v-for="(url, index) in scope.row.videos" :key="index" class="video-item">
                  <video
                    :src="baseURL + '/' + url"
                    controls
                    class="preview-video"
                  ></video>
                </div>
              </el-scrollbar>
            </el-popover>
          </el-space>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            type="text"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ich:heritage:edit']"
          >修改</el-button>
          <el-button
            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ich:heritage:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改非遗信息对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="heritageForm" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="非遗名称" prop="heritageName">
              <el-input v-model="form.heritageName" placeholder="请输入非遗名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="非遗编号" prop="heritageCode">
              <el-input v-model="form.heritageCode" placeholder="请输入非遗编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属类别" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="请选择所属类别">
                <el-option
                  v-for="item in categoryOptions"
                  :key="item.categoryId"
                  :label="item.categoryName"
                  :value="item.categoryId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="级别" prop="level">
              <el-select v-model="form.level" placeholder="请选择级别">
                <el-option
                  v-for="dict in ichLevel?.value?.ich_level || []"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="所属地区" prop="area">
          <el-input v-model="form.area" placeholder="请输入所属地区" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="历史背景" prop="history">
          <el-input v-model="form.history" type="textarea" placeholder="请输入历史背景" />
        </el-form-item>
        <el-form-item label="传承情况" prop="inheritanceStatus">
          <el-input v-model="form.inheritanceStatus" type="textarea" placeholder="请输入传承情况" />
        </el-form-item>

        <!-- 添加多媒体资料上传部分 -->
        <el-divider content-position="left">多媒体资料</el-divider>
        <el-row>
          <el-col :span="24">
            <el-form-item label="图片资料" prop="images">
              <el-upload
                v-model:file-list="imageList"
                :action="uploadImgUrl"
                list-type="picture-card"
                :headers="headers"
                :before-upload="beforeUpload"
                :on-success="handleImgSuccess"
                :on-remove="handleImgRemove"
                multiple
              >
                <el-icon><Plus /></el-icon>
                <template #tip>
                  <div class="el-upload__tip">支持jpg/png文件，且不超过5MB</div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="视频资料" prop="videos">
              <el-upload
                v-model:file-list="videoList"
                :action="uploadVideoUrl"
                :headers="headers"
                :before-upload="beforeVideoUpload"
                :on-success="handleVideoSuccess"
                :on-remove="handleVideoRemove"
                multiple
              >
                <el-button type="primary">上传视频</el-button>
                <template #tip>
                  <div class="el-upload__tip">支持mp4格式视频，且不超过50MB</div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Heritage">
import { listHeritage, getHeritage, delHeritage, addHeritage, updateHeritage } from "@/api/ich/heritage";
import { listCategory } from "@/api/ich/category";
import { getCurrentInstance, ref, reactive, toRefs, watch } from 'vue';
import { useDict } from "@/hooks/useDict";
import { getToken } from "@/utils/auth";
import { Plus } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance();
const baseURL = import.meta.env.VITE_APP_BASE_API;

// 获取字典数据
const ichLevel = ref({});

// 初始化字典数据
async function initDict() {
  const dictData = await proxy.useDict("ich_level");
  ichLevel.value = dictData;
}

// 监听字典数据变化
watch(() => ichLevel.value?.ich_level, (newVal) => {
  console.log('字典数据变化:', newVal);
}, { immediate: true });

const heritageList = ref([]);
const categoryOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    heritageName: undefined,
    heritageCode: undefined,
    categoryId: undefined,
    level: undefined,
    area: undefined
  },
  rules: {
    heritageName: [
      { required: true, message: "非遗名称不能为空", trigger: "blur" }
    ],
    heritageCode: [
      { required: true, message: "非遗编号不能为空", trigger: "blur" }
    ],
    categoryId: [
      { required: true, message: "所属类别不能为空", trigger: "change" }
    ],
    level: [
      { required: true, message: "级别不能为空", trigger: "change" }
    ]
  },
  // 上传相关变量
  uploadImgUrl: baseURL + "/system/heritage/upload/image",
  uploadVideoUrl: baseURL + "/system/heritage/upload/video",
  headers: ref({ Authorization: "Bearer " + getToken() }),
  imageList: ref([]),
  videoList: ref([])
});

const { queryParams, form, rules, uploadImgUrl, uploadVideoUrl, headers, imageList, videoList } = toRefs(data);

/** 查询类别列表 */
function getCategories() {
  listCategory().then(response => {
    categoryOptions.value = response.rows;
  });
}

/** 查询非遗信息列表 */
function getList() {
  loading.value = true;
  listHeritage(queryParams.value).then(response => {
    heritageList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    heritageId: undefined,
    heritageName: undefined,
    heritageCode: undefined,
    categoryId: undefined,
    level: undefined,
    description: undefined,
    history: undefined,
    inheritanceStatus: undefined,
    area: undefined,
    images: [],
    videos: []
  };
  imageList.value = [];
  videoList.value = [];
  proxy.resetForm("heritageForm");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryForm");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.heritageId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加非遗信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const heritageId = row.heritageId || ids.value;
  getHeritage(heritageId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改非遗信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["heritageForm"].validate(valid => {
    if (valid) {
      if (form.value.heritageId != undefined) {
        updateHeritage(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addHeritage(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const heritageIds = row.heritageId || ids.value;
  proxy.$modal.confirm('是否确认删除非遗信息编号为"' + heritageIds + '"的数据项？').then(function() {
    return delHeritage(heritageIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/heritage/export', {
    ...queryParams.value
  }, `heritage_${new Date().getTime()}.xlsx`);
}

/** 图片上传前的处理 */
function beforeUpload(file) {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isJPG) {
    proxy.$modal.msgError('上传图片只能是JPG/PNG格式!');
    return false;
  }
  if (!isLt5M) {
    proxy.$modal.msgError('上传图片大小不能超过5MB!');
    return false;
  }
  return true;
}

/** 视频上传前的处理 */
function beforeVideoUpload(file) {
  const isMP4 = file.type === 'video/mp4';
  const isLt50M = file.size / 1024 / 1024 < 50;

  if (!isMP4) {
    proxy.$modal.msgError('上传视频只能是MP4格式!');
    return false;
  }
  if (!isLt50M) {
    proxy.$modal.msgError('上传视频大小不能超过50MB!');
    return false;
  }
  return true;
}

/** 图片上传成功的处理 */
function handleImgSuccess(response, file) {
  if (response.code === 200) {
    form.value.images = form.value.images || [];
    form.value.images.push(response.data);
  } else {
    proxy.$modal.msgError(response.msg || '上传失败');
  }
}

/** 视频上传成功的处理 */
function handleVideoSuccess(response, file) {
  if (response.code === 200) {
    form.value.videos = form.value.videos || [];
    form.value.videos.push(response.data);
  } else {
    proxy.$modal.msgError(response.msg || '上传失败');
  }
}

/** 图片移除的处理 */
function handleImgRemove(file) {
  const index = form.value.images.indexOf(file.response.data);
  if (index > -1) {
    form.value.images.splice(index, 1);
  }
}

/** 视频移除的处理 */
function handleVideoRemove(file) {
  const index = form.value.videos.indexOf(file.response.data);
  if (index > -1) {
    form.value.videos.splice(index, 1);
  }
}

// 初始化
initDict();
getCategories();
getList();
</script>

<style scoped>
.preview-image {
  width: 100%;
  max-height: 150px;
  margin-bottom: 10px;
  cursor: pointer;
}

.preview-video {
  width: 100%;
  margin-bottom: 10px;
}

.video-item {
  margin-bottom: 15px;
}
</style> 